<template>
  <div>
    <el-card shadow="never">
      <el-form :inline="true" size="default" class="search-form">
        <div class="search">
          <el-form-item label="用户名">
            <el-input placeholder="请输入用户名" v-model="keyword" />
          </el-form-item>

          <div class="btn">
            <el-form-item>
              <el-button type="primary" @click="getHasUser(1)" :disabled="!keyword.length">搜索</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-card>

    <el-card shadow="never" class="user-table" v-loading="loading">
      <el-button type="primary" @click="deforeAddUser">添加用户</el-button>
      <el-popconfirm :title="`是否确定删除这些用户？`" confirmButtonText="确定" cancelButtonText="取消" @confirm="batchUser">
        <template #reference>
          <el-button type="danger">批量删除</el-button>
        </template>
      </el-popconfirm>

      <el-table border :data="records" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" />
        <el-table-column type="index" label="#" align="center" />
        <el-table-column label="id" prop="id" align="center" />
        <el-table-column label="用户名称" prop="username" align="center" show-overflow-tooltip />
        <el-table-column label="用户角色" prop="roleName" align="center" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createTime" align="center" show-overflow-tooltip />
        <el-table-column label="更新时间" prop="updateTime" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="280px" align="center">
          <template #="{ row }">
            <el-button type="primary" icon="User" title="分配角色" size="small" @click="beforeAssignRole(row)">分配角色</el-button>
            <el-button type="info" icon="Edit" title="编辑" size="small" @click="beforeEditUser(row)">编辑</el-button>
            <el-popconfirm :title="`是否确定删除该${row.username}吗？`" confirmButtonText="确定" cancelButtonText="取消" @confirm="deleteUser(row)">
              <template #reference>
                <el-button type="danger" icon="Delete" title="编辑" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:currentPage="pageNo"
        v-model:page-size="limit"
        :page-sizes="[5, 7, 9, 11]"
        layout="prev, pager, next, jumper, ->,sizes, total"
        @current-change="getHasUser"
        @size-change="sizeChange"
        :total="total"
        background
      />
    </el-card>

    <!-- 新增，修改用户账号 -->
    <dialog-form ref="dialogFormRef" @reload="$event = $event ? getHasUser(pageNo) : getHasUser()"></dialog-form>
    <assigRole ref="assigRoleRef" @reload="getHasUser()"></assigRole>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue'
  import type { UserResponseData, Records, User } from '@/api/acl/user/type'
  import { reqUserInfo, reqRemoveUser, reqSelectUser } from '@/api/acl/user'
  import { getElMessage } from '@/utils/message'
  import DialogForm from './components/dialogForm.vue'
  import assigRole from './components/assigRole.vue'
  import useLayoutSettingStore from '@/store/modules/setting'

  const pageNo = ref<number>(1)
  const limit = ref<number>(5)
  const total = ref<number>(0)
  const loading = ref<boolean>(false)
  const records = ref<Records>([])
  const dialogFormRef = ref<InstanceType<typeof DialogForm>>()
  const assigRoleRef = ref<InstanceType<typeof assigRole>>()
  const multipleSelection = ref<number[]>([])
  const keyword = ref<string>('')
  const curUser = ref<string>(localStorage.getItem('curUserName') || '')
  onMounted(() => {
    getHasUser()
  })

  async function getHasUser(pager = 1) {
    try {
      pageNo.value = pager
      loading.value = true
      const res: UserResponseData = await reqUserInfo(pageNo.value, limit.value, keyword.value)
      if (res.code === 200) {
        records.value = res.data.records
        total.value = res.data.total
      } else {
        getElMessage('获取用户列表数据失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    } finally {
      loading.value = false
    }
  }

  // 点击添加用户
  function deforeAddUser() {
    dialogFormRef.value?.open({})
    dialogFormRef.value?.formRef?.resetFields()
  }

  // 点击编辑用户
  function beforeEditUser(row: User) {
    dialogFormRef.value?.open(row)
  }

  // 点击分配角色
  function beforeAssignRole(row: User) {
    assigRoleRef.value?.open(row)
  }

  // 点击删除
  async function deleteUser(row: User) {
    try {
      const res: any = await reqRemoveUser(row.id as number)
      if (res.code === 200) {
        getElMessage('删除成功', 'success')
        if (curUser.value === row.username) {
          window.location.reload()
        } else {
          getHasUser(records.value.length ? pageNo.value : pageNo.value - 1)
        }
      } else {
        getElMessage('删除失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    }
  }

  // 点击批量删除
  async function batchUser() {
    try {
      if (!multipleSelection.value.length) return getElMessage('请选择要删除的用户', 'warning')

      const res: any = await reqSelectUser(multipleSelection.value)
      if (res.code === 200) {
        getElMessage('批量删除成功', 'success')

        getHasUser(records.value.length ? pageNo.value : pageNo.value - 1)
      } else {
        getElMessage('批量删除失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    }
  }

  // 重置
  const settingStore = useLayoutSettingStore()
  function reset() {
    settingStore.refresh = !settingStore.refresh
  }

  const handleSelectionChange = (val: Records) => {
    multipleSelection.value = val.map((o) => o.id) as number[]
  }

  function sizeChange(pageSize: number) {
    limit.value = pageSize
    getHasUser()
  }
</script>

<style lang="scss" scoped>
  .search-form {
    .search {
      display: flex;
      align-items: center;
      .btn {
        margin-left: auto;
      }
    }
  }
  .user-table {
    margin-top: 10px;
    .el-table {
      margin: 10px 0;
    }
  }
</style>
